package org.devio.rn.splashscreen;

import android.animation.Animator;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Build;
import android.support.annotation.Nullable;
import android.view.Display;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.airbnb.lottie.LottieAnimationView;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;

import java.lang.ref.WeakReference;

/**
 * SplashScreen
 * 启动屏
 * from：http://www.devio.org
 * Author:CrazyCodeBoy
 * GitHub:https://github.com/crazycodeboy
 * Email:crazycodeboy@gmail.com
 */
public class SplashScreen {

    public static ReactContext myContext;
    private static LottieAnimationView mLottieAnimationView;
    private static Dialog mSplashDialog;
    private static WeakReference<Activity> mActivity;

    /**
     * 打开启动屏
     */
    public static void show(final Activity activity, final int themeResId) {
        if (activity == null) return;
        mActivity = new WeakReference<Activity>(activity);
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!activity.isFinishing()) {

                    Display display = activity.getWindowManager().getDefaultDisplay();
                    Context context = activity.getBaseContext();

                    mLottieAnimationView = new LottieAnimationView(context);
                    LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
                    mLottieAnimationView.setLayoutParams(layoutParams);

                    mLottieAnimationView.setMinimumHeight(display.getHeight());
                    mLottieAnimationView.setMinimumWidth(display.getWidth());


                    mLottieAnimationView.setImageAssetsFolder("animate/images/");
                    mLottieAnimationView.setAnimation("animate/data.json");
                    mLottieAnimationView.setProgress(0f);
                    mLottieAnimationView.setRepeatCount(0);
                    mLottieAnimationView.useHardwareAcceleration(true);
                    mLottieAnimationView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);

                    mLottieAnimationView.addAnimatorListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animator) {

                        }

                        @Override
                        public void onAnimationEnd(Animator animator) {
                            WritableMap params = Arguments.createMap();
                            SplashScreen.sendEvent(myContext, "SplashScreenHide", params);
                        }

                        @Override
                        public void onAnimationCancel(Animator animator) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animator) {

                        }
                    });
                    mLottieAnimationView.playAnimation();

                    mSplashDialog = new Dialog(activity, themeResId);
                    mSplashDialog.setContentView(R.layout.launch_screen);
                    mSplashDialog.addContentView(mLottieAnimationView, layoutParams);


                    mSplashDialog.setCancelable(false);

                    if (!mSplashDialog.isShowing()) {
                        mSplashDialog.show();
                    }
                }
            }
        });
    }

    /**
     * 打开启动屏
     */
    public static void show(final Activity activity, final boolean fullScreen) {
        int resourceId = fullScreen ? R.style.SplashScreen_Fullscreen : R.style.SplashScreen_SplashTheme;

        show(activity, resourceId);
    }

    /**
     * 定义发送事件的函数
     */
    private static void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params)
    {
        reactContext
            .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
            .emit(eventName, params);
    }

    /**
     * 打开启动屏
     */
    public static void show(final Activity activity) {
        show(activity, false);
    }

    /**
     * 关闭启动屏
     */
    public static void hide(Activity activity) {
        if (activity == null) {
            if (mActivity == null) {
                return;
            }
            activity = mActivity.get();
        }

        if (activity == null) return;

        final Activity _activity = activity;

        _activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mSplashDialog != null && mSplashDialog.isShowing()) {

                    final int fadeSplashScreenDuration = 300;
                    AlphaAnimation fadeOut = new AlphaAnimation(1, 0);
                    fadeOut.setInterpolator(new DecelerateInterpolator());
                    fadeOut.setDuration(fadeSplashScreenDuration);

                    mLottieAnimationView.setAnimation(fadeOut);
                    mLottieAnimationView.startAnimation(fadeOut);

                    fadeOut.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            boolean isDestroyed = false;

                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                                isDestroyed = _activity.isDestroyed();
                            }
                            if (mSplashDialog != null && mSplashDialog.isShowing()) {
                                if (!_activity.isFinishing() && !isDestroyed) {
                                    mSplashDialog.dismiss();
                                }
                                mSplashDialog = null;
                                mLottieAnimationView = null;
                            }
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {
                        }
                    });
                }
            }
        });
    }
}
